package top.zsyle.basic.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import top.zsyle.basic.eum.JwtRsaHolder;
import top.zsyle.basic.jwt.JwtUtils;
import top.zsyle.basic.jwt.Payload;
import top.zsyle.basic.jwt.RsaUtils;
import top.zsyle.basic.jwt.UserInfo;
import top.zsyle.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

@Slf4j
public class LoginContext {


    public static Logininfo getLogininfo(HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        // 如果token存在 去reids中查询
        PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(JwtRsaHolder.INSTANCE.getJwtPetPubData()).getFile());
        Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
        if (null == payload.getUserInfo()){
            log.info("从jwt中获取用户信息为null");
        }
        return payload.getUserInfo().getLogininfo();
    }

    public static UserInfo getUserInfo(){
        UserInfo userInfo = ThreadLocalUtil.getUserInfo();
        UserInfo result = new UserInfo();
        result.setLogininfo(userInfo.getLogininfo());
        result.setShop(userInfo.getShop());
        ThreadLocalUtil.remove();
        return result;
    }

}
